/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package towerz.system;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Hashtable;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.io.file.FileConnection;

/**
 *
 * @author TimotiusNC
 */
public class MobileHttp {
	private MobileHttp(){
		
	}

	public static MobileHttp getInstance(){
		if(m_instance == null)
			m_instance = new MobileHttp();

		return m_instance;
	}

	public String sendUsingPost(String url, Hashtable param){
		HttpConnection httpConn = null;
		InputStream	is	= null;
		OutputStream os	= null;
		StringBuffer sb = null; //retval
		
		try {
			//System.out.println("url = " + url);
			httpConn = (HttpConnection) Connector.open(url, Connector.READ_WRITE);

			httpConn.setRequestMethod(HttpConnection.POST);
			httpConn.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.1");
			httpConn.setRequestProperty("Accept_Language", "en-US");
			httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

			//Create and append parameter
			if(param != null){
				os = httpConn.openDataOutputStream();

				StringBuffer params = new StringBuffer();
				Enumeration en = param.keys();
				while(en.hasMoreElements()){
					String key = (String)en.nextElement();
					if(en.hasMoreElements())
						params.append(key).append("=").append(param.get(key)).append("&");
					else
						params.append(key).append("=").append(param.get(key));
				}
				//System.out.println("params = " + params.toString());

				os.write(params.toString().getBytes());
			}

			//Get connection information
			getConnectionInformation(httpConn);

			//Read Response
			sb = new StringBuffer();
			is = httpConn.openDataInputStream();
			int chr;
			while((chr = is.read()) != -1)
				sb.append((char) chr);

			//System.out.println("Response = " + sb.toString());
		} catch (IOException ex) {
			sb.append("error");
		} finally {
			try {
				if(is != null)
					is.close();
				if(os != null)
					os.close();
				if(httpConn != null)
					httpConn.close();
			} catch (IOException ex) {}
		}

		return sb.toString();
	}

	public String sendUsingGet(String url, Hashtable param){
		HttpConnection httpConn = null;
		InputStream	is	= null;
		OutputStream os	= null;
		StringBuffer sb = null; //retval
		StringBuffer urlBuffer = null;

		try {
			//System.out.println("url = " + url);
			urlBuffer = new StringBuffer();
			urlBuffer.append(url);

			//Create and append parameter
			if(param != null){
				StringBuffer params = new StringBuffer();
				Enumeration en = param.keys();
				while(en.hasMoreElements()){
					String key = (String)en.nextElement();
					if(en.hasMoreElements())
						params.append(key).append("=").append(param.get(key)).append("&");
					else
						params.append(key).append("=").append(param.get(key));
				}

				urlBuffer.append("?").append(params.toString());
			}

			//System.out.println("params = " + urlBuffer.toString());
			httpConn = (HttpConnection) Connector.open(urlBuffer.toString(), Connector.READ_WRITE);

			httpConn.setRequestMethod(HttpConnection.GET);
			httpConn.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.1");

			//Get connection information
			getConnectionInformation(httpConn);

			//Read Response
			sb = new StringBuffer();
			is = httpConn.openDataInputStream();
			int chr;
			while((chr = is.read()) != -1)
				sb.append((char) chr);

			//System.out.println("Response = " + sb.toString());
		} catch (IOException ex) {
			sb.append("error");
		} finally {
			try {
				if(is != null)
					is.close();
				if(os != null)
					os.close();
				if(httpConn != null)
					httpConn.close();
			} catch (IOException ex) {}
		}

		return sb.toString();
	}

	public byte[] download(String URL){
        byte[] retval = null;

        HttpConnection connection = null;
        DataInputStream inputStream = null;

        try {
            connection = (HttpConnection) Connector.open(URL); //Open HTTP Connection
			//System.out.println("Status line code : " + connection.getResponseCode());
			//System.out.println("Status line message : " + connection.getResponseMessage());

            if(connection.getResponseCode() == HttpConnection.HTTP_OK){
            //System.out.println(connection.getHeaderField(0) + "-" + connection.getHeaderFieldKey(0));
            //System.out.println("Header Field Date : " + connection.getHeaderField("date"));
            //System.out.println("Get File : " + connection.getFile());

                String str;
                inputStream = connection.openDataInputStream();

                int length = (int) connection.getLength();

                if(length != -1){
					//System.out.println("length != -1");
                    retval = new byte[length];

                    inputStream.readFully(retval);

                    str = new String(retval);
                } else {
                    ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
                    int ch;
                    while ((ch = inputStream.read()) != -1)
                        bytestream.write(ch);

                    str = new String(bytestream.toByteArray());
                    bytestream.close();
                }
            }
        } catch (IOException ex) {}
		finally {
            if(inputStream != null){
                try{
                    inputStream.close();
                } catch (Exception error){}
            }
            if(connection != null){
                try{
                    connection.close();
                } catch (Exception error){}
            }
        }

        return retval;
    }

    public void saveByteToFolder(byte[] bytes, String pathAndFileName){
        DataOutputStream dOStream = null;

        try {
            FileConnection fc = (FileConnection) Connector.open(pathAndFileName);

            if(!fc.exists())
                fc.create();
            else {
                fc.delete();
                fc.create();
            }

            dOStream = fc.openDataOutputStream();
            dOStream.write(bytes);

            fc.close();
        } catch (IOException ex) {}
		finally {
            if(dOStream != null){
                try{
                    dOStream.close();
                } catch (Exception error){}
            }
        }
    }

	void getConnectionInformation(HttpConnection hc) {
		try{
			hc.getResponseCode();
		} catch(IOException ex){}
		
		/*try {
			System.out.println("\tStatus line code : " + hc.getResponseCode());
			System.out.println("\tStatus line message : " + hc.getResponseMessage());
		} catch (IOException ex) {}

		System.out.println("\tRequest Method for this connection is " + hc.getRequestMethod());
		System.out.println("\tURL in this connection is " + hc.getURL());
		System.out.println("\tProtocol for this connection is " + hc.getProtocol()); // It better be HTTP:)
		System.out.println("\tThis object is connected to " + hc.getHost() + " host");
		System.out.println("\tHTTP Port in use is " + hc.getPort());
		System.out.println("\tQuery parameter in this request are  " + hc.getQuery());*/
    }

	//ATTRIBUTES
	private static MobileHttp m_instance;
}
